package com.tsite.service.common.security;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import com.tsite.entity.Role;
import com.tsite.entity.User;

@Component
public class UserDetailsAuthenticationProviderImpl implements
		AuthenticationProvider {

	@Autowired
	private UserDetailsServiceImpl userDetailsService;
	
	
	@Override
	public Authentication authenticate(Authentication authentication)
			throws AuthenticationException {
		String username = authentication.getName();
		String password = (String)authentication.getCredentials();
//		WebAuthenticationDetailsX paramEx = (WebAuthenticationDetailsX) authentication.getDetails();
//		String mso_ios = paramEx.getMso_ios();
		
		UserDetailsImpl userDetailsImpl= (UserDetailsImpl)userDetailsService.loadUserByUsername(username);
		UserDetails userDetails = buildUserDetails(userDetailsImpl);
		
		if (userDetails == null) {
            throw new BadCredentialsException("Username not found.");
        }
 
        if (!PasswordEncoderFacade.matches(password, userDetails.getPassword())) {
            throw new BadCredentialsException("Wrong password.");
        }
 
        Collection<? extends GrantedAuthority> authorities = userDetails.getAuthorities();
 
        return new UsernamePasswordAuthenticationToken(username, password, authorities);
	}

	@Override
	public boolean supports(Class<?> authentication) {
		return true;
	}
	
	private UserDetails buildUserDetails(UserDetailsImpl userDetails){
		if(userDetails == null)
			return null;
		
		User user = userDetails.getUser();		
		UserDetailsImpl userInfo = new UserDetailsImpl(user);		
		List<GrantedAuthorityImpl> grantedAuthorities = new ArrayList<GrantedAuthorityImpl>();
		
		Iterator<Role> roles = user.getRoles().iterator();
		while(roles.hasNext()){
			Role role = roles.next();
			GrantedAuthorityImpl grantedRole = new GrantedAuthorityImpl();
			grantedRole.setName(role.getRole());
			grantedAuthorities.add(grantedRole);
		}
		
		userInfo.setAuthorities(grantedAuthorities);
		
		return userInfo;		
	}

}
